package com.css.fxfzxczh.modules.downloadLegend.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzxczh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzxczh.base.response.RestResponse;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.downloadLegend.Vo.LegendVo;
import com.css.fxfzxczh.modules.downloadLegend.Vo.RequestVO;
import com.css.fxfzxczh.modules.downloadLegend.Vo.ResponseVO;
import com.css.fxfzxczh.modules.downloadLegend.entity.*;
import com.css.fxfzxczh.modules.downloadLegend.service.DownloadsFile;
import com.css.fxfzxczh.modules.downloadLegend.service.SupergraphService;
import com.css.fxfzxczh.modules.resultsManagement.entity.MapManagementEntity;
import com.css.fxfzxczh.modules.resultsManagement.entity.MapTemplate;
import com.css.fxfzxczh.modules.resultsManagement.repository.MapManagementRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;


@Service
@Slf4j
public class SupergraphServiceImpl implements SupergraphService {
    @Resource
    RestTemplateUtil restTemplateUtil;

    @Value("${image.ctLocalDir}")
    private String ctLocalDir;

    @Resource
    private DownloadsFile downloadsFile;
    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;
    @Resource
    private SUserService sUserService;
    @Resource
    private MapManagementRepository mapManagementRepository;
    @Resource
    RestTemplate restTemplate;
    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public RestResponse supergraph(RequestVO requestVO) {
        RestResponse restResponse = null;
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl") + "/webprinting/rest/webprinting/v1/jobs.json";
        JSONObject requestJsonVo = (JSONObject) JSONObject.toJSON(requestVO);
        String json = JSONObject.toJSONString(requestJsonVo);
        log.info(json);
        Map map = JSONObject.parseObject(json, Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest(url, map);
        String body = stringResponseEntity.getBody();
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath();
            //获取出图任务状态
            path = getMapLayerPrintJob(path);
            if(path.equals("出图失败")){
                return RestResponse.fail("出图失败！");
            }
            path = responseVO.get(0).getPath() + "/" + "result";
            String savePath = ctLocalDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            restResponse = downloadsFile.downloadByUrl(path, savePath);
        }
        File file = new File(ctLocalDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }

        return restResponse;
    }

    //获取出图任务状态
    public String getMapLayerPrintJob(String path) {
        String result = null;
        try {
            String dataUrl = path + ".json";
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "出图失败";
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            /*if (body == null) {
                return "出图失败";
            }*/
            if (body.getString("status").equals("ERROR")) {
                return "出图失败";
            }
            while (!body.getString("status").equals("ERROR") && !body.getString("status").equals("FINISHED")) {
                Thread.sleep(1000);
                //获取任务执行百分比
                result = getMapLayerPrintJob(path);
                if(result.equals("出图成功") || result.equals("出图失败")){
                    break;
                }
            }
            if(body.getString("status").equals("FINISHED")){
                return "出图成功";
            }else if (body.getString("status").equals("ERROR")) {
                return "出图失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = getMapLayerPrintJob(path);
        }
        return result;
    }

    //一键打印出图
    @Override
    public RestResponse handle(LegendVo legendVo) {
        try{
            //事件ID
            String xsemId = legendVo.getXsemId();
            //查询地震事件
            String sql = "select * from xczh_seismic_event_management where xsem_id = ? ";
            EarEveManage earEveManage = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(EarEveManage.class), xsemId);
            legendVo.setEarEveManage(earEveManage);
            String sql2 = "select st_extent(geom) from xzch_draw_seismic_influence where xsem_id = ? and del_flag = '0'";
            String extent = jdbcTemplate.queryForObject(sql2, String.class,xsemId);
            String sql3 = "select ST_AsText(ST_Centroid(ST_extent(geom))) from xzch_draw_seismic_influence where xsem_id = ? and del_flag = '0'";
            String center = jdbcTemplate.queryForObject(sql3, String.class,xsemId);
            String[] split = extent.substring(4, extent.length() - 1).split(",");
            String[] s1 = split[0].split(" ");
            String[] s2 = split[1].split(" ");
            String leftX = s1[0];
            String leftY = s1[1];
            String rightX = s2[0];
            String rightY = s2[1];
            List<MapTemplate> mapTemplates = new ArrayList<>();
            MapTemplate mapTemplate = new MapTemplate();
            mapTemplate.setMapType("地震烈度图");
            mapTemplate.setDictType("地震烈度图");
            mapTemplate.setDictCode("DrawSeismicInfluence");
            mapTemplate.setFormat("3");//横版带简介
            mapTemplates.add(mapTemplate);
            legendVo.setMapTemplates(mapTemplates);
            String formatType = "横版带简介";
            int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY),formatType);
            String[] s = center.substring(6, center.length() - 1).split(" ");
            String centerX = s[0];
            String centerY = s[1];
            Map<String, Double> hashMap = new HashMap<>();
            hashMap.put("leftX", Double.valueOf(leftX));
            hashMap.put("leftY", Double.valueOf(leftY));
            hashMap.put("rightX", Double.valueOf(rightX));
            hashMap.put("rightY", Double.valueOf(rightY));
            hashMap.put("centerX", Double.valueOf(centerX));
            hashMap.put("centerY", Double.valueOf(centerY));
            hashMap.put("level", Double.valueOf(level));
            return toData(legendVo, hashMap);
        }catch (Exception e){
            return RestResponse.fail(503,"出图失败");
        }
    }

    //根据经纬度范围获取level值
    public int getLevel(double leftBottom_X,double leftBottom_Y,double rightTop_X,double rightTop_Y,String formatType) {
        int level = 4;//默认级别4
        double minLon = leftBottom_X;
        double minLat = leftBottom_Y;
        double maxLon = rightTop_X;
        double maxLat = rightTop_Y;
        //获取最大差值
        double diffLon = maxLon - minLon;
        double diffLat = maxLat - minLat;
        double diffMax = diffLon;
        if(diffLon < diffLat){
            diffMax = diffLat;
        }
//        int diff = Math.round(diffMax);
//        long round = Math.round(diffMax);
        //1-18缩放级别zoom
        /*int[] levelArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
        Double[] diffArr = {360.0,180.0,90.0,45.0,22.0,11.0,5.0,2.5,1.25, 0.6,0.3,0.15,0.07,0.03,0.015,0.007,0.0003,0.00015};
        for (int i = 0; i < diffArr.length; i++) {
            if (diffMax - diffArr[i] >= 0) {
                level = levelArr[i];
                break;
            }
        }*/
        int width,height;
        if(formatType.equals("横版")){
            width = 1510;
            height = 1020;
        }else if(formatType.equals("竖版")){//竖版
            width = 1150;
            height = 1230;
        }else{//横版带简介
            width = 1160;
            height = 1010;
        }
        //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
        level = getBoundsZoomLevel(leftBottom_X,leftBottom_Y,rightTop_X,rightTop_Y,width, height);

        return level;
    }

    final static int GLOBE_WIDTH = 256;
    final static int ZOOM_MAX = 18;
    //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
    public static int getBoundsZoomLevel(double leftBottom_X,double leftBottom_Y,double rightTop_X,double rightTop_Y,
                                         int width, int height) {
        double latFraction = (latRad(rightTop_Y) - latRad(leftBottom_Y)) / Math.PI;
        double lngDiff = rightTop_X - leftBottom_X;
        double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
        double latZoom = zoom(height, GLOBE_WIDTH, latFraction);
        double lngZoom = zoom(width, GLOBE_WIDTH, lngFraction);
        double zoom = Math.min(Math.min(latZoom, lngZoom),ZOOM_MAX);
        return (int)(zoom);
    }
    private static double latRad(double lat) {
        double sin = Math.sin(lat * Math.PI / 180);
        double radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
        return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
    }
    private static double zoom(double mapPx, double worldPx, double fraction) {
        final double LN2 = .693147180559945309417;
        return (Math.log(mapPx / worldPx / fraction) / LN2);
    }

    private RestResponse toData(LegendVo legendVo, Map<String, Double> hashMap) {
        List<MapTemplate> mapTemplates = legendVo.getMapTemplates();
        String returnMsg = "";
        int successCount = 0;
        for (MapTemplate mapTemplate : mapTemplates) {
            String result = toDataMapTemplate(legendVo,hashMap,mapTemplate);
            if(!result.equals("出图成功")){
                if (PlatformObjectUtils.isNotEmpty(returnMsg)) {
                    returnMsg += "、";
                }
                returnMsg += result;
            }else{
                successCount++;
            }
        }
        if (PlatformObjectUtils.isNotEmpty(returnMsg)) {
            returnMsg += "出图失败！";
            if(successCount>0){
                returnMsg += "其余选择的图件出图成功";
            }else{
                returnMsg = "全部图件出图失败";
            }
            return RestResponse.fail(503,returnMsg);
        }else{
            returnMsg = "出图成功！";
            return RestResponse.succeed(returnMsg);
        }
    }

    private String toDataMapTemplate(LegendVo legendVo, Map<String, Double> hashMap,MapTemplate mapTemplate) {
        String result = "出图成功";
        String mapType = mapTemplate.getMapType();
        try{
            //打印1张图
            RequestVO requestVO = getRequestVO(legendVo,mapTemplate,hashMap);
            RestResponse response = supergraph(requestVO);
            if (response.getCode() != 200) {
                return mapType;
            }
            String attachId = response.getData().toString();
            //获取图件实体
            MapManagementEntity entity = getEntity(attachId, legendVo, mapTemplate);
            //一键出图
            MapManagementEntity byLabel = mapManagementRepository.getByLabel(entity.getXsemId(), entity.getMapLabel());
            if (byLabel == null) {
                mapManagementRepository.saveMap(entity);
            } else {
                byLabel.setMapDescription(entity.getMapDescription());
                byLabel.setMapName(entity.getMapName());
                byLabel.setMapLabel(entity.getMapLabel());
                byLabel.setUnit(entity.getUnit());
                byLabel.setAttachId(entity.getAttachId());
                byLabel.setUpdateUser(PlatformSessionUtils.getUserId());
                byLabel.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                mapManagementRepository.update(byLabel);
            }
        }catch (Exception e){
            result = mapType;
            log.error(mapType+"出图失败!",e);
        }

        return result;
    }

    //设置打印出图请求体
    private RequestVO getRequestVO(LegendVo legendVo,MapTemplate mapTemplate, Map<String, Double> hashMap) {
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(mapTemplate.getTemplateId());
        RequestVO requestVO = new RequestVO();
        LayoutOptions layoutOptions = new LayoutOptions();
//        layoutOptions.setTemplateName("LayoutTemplatetest");
        String templateName = "Administrative_Active_Fault-hx1012";//测试横版带地震烈度图说明
        String format = mapTemplate.getFormat();//版式  0横板  1竖版  2无 3横版带简介
        if(attach!=null){
            String[] split = attach.getAttachPath().split("/");
            String realAttachName = split[split.length - 1];
//        layoutOptions.setTemplateName(realAttachName);
        }
        layoutOptions.setTemplateName(templateName);//test
//        layoutOptions.setTitle(mapTemplate.getDictType());
        String title = getTitleByDictCodeTask(legendVo,mapTemplate);
        layoutOptions.setTitle(title);//标题
        layoutOptions.setAuthor("制图单位："+legendVo.getUnit());//制图单位
        String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
        layoutOptions.setTime("制图时间:"+date);//制图时间
        layoutOptions.setSummaryText(legendVo.getSummaryText());//简介
        ScaleBarOptions scaleBarOptions = new ScaleBarOptions("","BAR",5,"METER");
        layoutOptions.setScaleBarOptions(scaleBarOptions);
//        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://NorthArrow.svg");
        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://ARROW_RIGHT_FILL_WITH_COLOR.svg");
        layoutOptions.setNorthArrowOptions(northArrowOptions);
        MapGridOptions mapGridOptions = new MapGridOptions();//经纬度网格边框
        mapGridOptions.setOriginX(-180);
        mapGridOptions.setOriginY(-90);
        mapGridOptions.setCellWidth(10);
        mapGridOptions.setCellHeight(10);
        mapGridOptions.setMarkType("DMS");
        layoutOptions.setMapGridOptions(mapGridOptions);
        LegendOption legendOption = new LegendOption();
        legendOption.setTitle("图 例");
        String dictCode = mapTemplate.getDictCode();//出图类型字典code
        //根据dictCode、任务ID获取临时图层URL的Map
        Map<String,String> tempLayerUrlMap = getTempLayerUrlMapByDictCode(dictCode,legendVo);
        List<Layerr> layerrs = getLayerrs(dictCode,legendVo,tempLayerUrlMap);
        legendOption.setLayers(layerrs);
        layoutOptions.setLegendOptions(legendOption);
        requestVO.setLayoutOptions(layoutOptions);
        ExportOptions exportOptions = new ExportOptions("png", 120.0);
        requestVO.setExportOptions(exportOptions);
        Content content = new Content();
        content.setType("WEBMAP");
        com.css.fxfzxczh.modules.downloadLegend.entity.Value value = new com.css.fxfzxczh.modules.downloadLegend.entity.Value();
        leftAndright leftBottom = new leftAndright(hashMap.get("leftX"), hashMap.get("leftY"));
        leftAndright rightTop = new leftAndright(hashMap.get("rightX"), hashMap.get("rightY"));
        Extent extent = new Extent(leftBottom, rightTop);
        value.setExtent(extent);
        value.setMaxScale("1:2130.3378410848");
        value.setLevel(hashMap.get("level"));
        if(format.equals("3")) {//3横版带简介
            int level = getLevel(hashMap.get("leftX"), hashMap.get("leftY"), hashMap.get("rightX"), hashMap.get("rightY"),"横版带简介");
            value.setLevel(Double.valueOf(level));
        }
//        value.setLevel(11.0);
        leftAndright center = new leftAndright(hashMap.get("centerX"), hashMap.get("centerY"));
        value.setCenter(center);
//        BaseLayer baseLayer = new BaseLayer("TILE", "China", "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/data_faultage@fxfzypg");
//        value.setBaseLayer(baseLayer);
        List<Layer> layers = getLayers(dictCode,legendVo,tempLayerUrlMap);
        value.setLayers(layers);
        value.setDescription("");
        value.setProjection("EPSG:4490");
        value.setMinScale("1:591658710.909131");
        value.setTitle("China");
        value.setVersion("2.3.0");
        content.setValue(value);
        requestVO.setContent(content);
        return requestVO;
    }

    private List<Layer> getLayers(String dictCode,LegendVo legendVo,Map<String,String> tempLayerUrlMap) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<Layer> layers =null;
        //地震烈度图
        if ("DrawSeismicInfluence".equals(dictCode)) {
            String url1 = url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
            /*String url1 = url + "/map-fxfzypg/rest/maps/district_boundary_province_text@fxfzypg";
            String url2 = url + "/map-fxfzypg/rest/maps/district_boundary_city_text@fxfzypg";
            String url3 = url + "/map-fxfzypg/rest/maps/district_boundary_county_text@fxfzypg";
            String url4 = url + "/map-fxfzypg/rest/maps/district_boundary_province@fxfzypg";
            String url5 = url + "/map-fxfzypg/rest/maps/district_boundary_city@fxfzypg";
            String url6 = url + "/map-fxfzypg/rest/maps/district_boundary_county@fxfzypg";*/
//            String url7 = url + "/map-fxfzypg/rest/maps/data_faultage@fxfzypg";
            //获取临时图层--地震烈度绘制影响场
            String url8 = tempLayerUrlMap.get("xzch_draw_seismic_influence");
            //获取临时图层--地震震中
            String url9 = tempLayerUrlMap.get("xczh_seismic_event_management");

            Layer layer1 = new Layer("TILE",true,"district_boundary_china",url1);
            /*Layer layer1 = new Layer("TILE",true,"district_boundary_province_text",url1);
            Layer layer2 = new Layer("TILE",true,"district_boundary_city_text",url2);
            Layer layer3 = new Layer("TILE",true,"district_boundary_county_text",url3);
            Layer layer4 = new Layer("TILE",true,"district_boundary_province",url4);
            Layer layer5 = new Layer("TILE",true,"district_boundary_city",url5);
            Layer layer6 = new Layer("TILE",true,"district_boundary_county",url6);*/
//            Layer layer7 = new Layer("TILE",true,"data_faultage",url7);
            Layer layer8 = new Layer("TILE",true,"xzch_draw_seismic_influence",url8);
            Layer layer9 = new Layer("TILE",true,"xczh_seismic_event_management",url9);

            //获取临时图层--断层
            String url10 = tempLayerUrlMap.get("jc_fault");
            Layer layer10 = new Layer("TILE",true,"jc_fault",url10);


            layers = Arrays.asList(layer8,layer10,layer1,layer9);
        }
        if (layers==null){
            String url1 = url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
            Layer layer = new Layer("TILE",true,"district_boundary_china",url1);
            layers = Arrays.asList(layer);
        }
        return layers;
    }

    private List<Layerr> getLayerrs(String dictCode,LegendVo legendVo,Map<String,String> tempLayerUrlMap) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<Layerr> layerrs =null;
        //地震烈度图
        if ("DrawSeismicInfluence".equals(dictCode)) {
            /*List<String> strings1 =Arrays.asList("district_boundary_province_text@fxfzypg");
            Layerr layerr1 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_province_text@fxfzypg",strings1);

            List<String> strings2 =Arrays.asList("district_boundary_city_text@fxfzypg");
            Layerr layerr2 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_city_text@fxfzypg",strings2);

            List<String> strings3 =Arrays.asList("district_boundary_county_text@fxfzypg");
            Layerr layerr3 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_county_text@fxfzypg",strings3);

            List<String> strings4 =Arrays.asList("district_boundary_province@fxfzypg");
            Layerr layerr4 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_province@fxfzypg",strings4);

            List<String> strings5 =Arrays.asList("district_boundary_city@fxfzypg");
            Layerr layerr5 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_city@fxfzypg",strings5);

            List<String> strings6 =Arrays.asList("district_boundary_county@fxfzypg");
            Layerr layerr6 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_county@fxfzypg",strings6);*/
            List<String> strings1 = Arrays.asList("district_boundary_province@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_province_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county_text@fxfzypg@@district_boundary_china@fxfzypg");
            Layerr layerr1 = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg",strings1);

//            List<String> strings7 =Arrays.asList("data_faultage@fxfzypg@@data_faultage@fxfzypg");
//            Layerr layerr7 = new Layerr(url+"/map-fxfzypg/rest/maps/data_faultage@fxfzypg",strings7);
            //获取临时图层--地震烈度绘制影响场
            String tempLayerUrl = tempLayerUrlMap.get("xzch_draw_seismic_influence");
            List<String> strings8 = new ArrayList<>();
            Layerr layerr8 = new Layerr(tempLayerUrl,strings8);
            //获取临时图层--地震震中
            String tempLayerUrl2 = tempLayerUrlMap.get("xczh_seismic_event_management");
            List<String> strings9 = new ArrayList<>();
            Layerr layerr9 = new Layerr(tempLayerUrl2,strings9);

            //获取临时图层--断层
            String tempLayerUrl3 = tempLayerUrlMap.get("jc_fault");
            //获取图层图例（除文字标签）
            Layerr layerr10 = getLayerrByLayerNameUrl(tempLayerUrl3);

            layerrs = Arrays.asList(layerr8,layerr10,layerr1,layerr9);
        }

        if (layerrs==null){
            List<String> strings = Arrays.asList("district_boundary_province@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_province_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county_text@fxfzypg@@district_boundary_china@fxfzypg");
            Layerr layerr = new Layerr(url+"/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg",strings);
//            List<String> strings =Arrays.asList("data_faultage@fxfzypg");
//            Layerr layerr = new Layerr(url+"/map-fxfzypg/rest/maps/data_faultage@fxfzypg",strings);
            layerrs = Arrays.asList(layerr);
        }
        return layerrs;
    }

    private MapManagementEntity getEntity(String imageId, LegendVo legendVo, MapTemplate mapTemplate) {
        MapManagementEntity mapManagementEntity = new MapManagementEntity();
        mapManagementEntity.setMapId(UUIDGenerator.getUUID());
        mapManagementEntity.setXsemId(legendVo.getXsemId());
        mapManagementEntity.setXsemName(legendVo.getEarEveManage().getEventName());
        mapManagementEntity.setUnit(legendVo.getUnit());//制图单位
        mapManagementEntity.setAttachId(imageId);
        //名称 暂时搞成类型
        String dictType = mapTemplate.getDictType();
        mapManagementEntity.setMapName(dictType);
        String dictCode = mapTemplate.getDictCode();
        String order = getByCode(dictCode);
        mapManagementEntity.setMapLabel(order);
        mapManagementEntity.setMapDescription(dictType);
        mapManagementEntity.setDelFlag(YNEnum.N.toString());
        mapManagementEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        mapManagementEntity.setUploadTime(PlatformDateUtils.getCurrentTimestamp());
        String userId = PlatformSessionUtils.getUserId();
        mapManagementEntity.setCreateUser(userId);
        if (PlatformObjectUtils.isNotEmpty(userId)) {
            String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            if (sUser != null) {
                mapManagementEntity.setUploader(sUser.getUserName());
            }
        }
        return mapManagementEntity;
    }

    private String getByCode(String dictCode) {
        if ("DrawSeismicInfluence".equals(dictCode)) return "0";

        return "1";
    }

    //获取图层图例（除文字标签）
    public Layerr getLayerrByLayerNameUrl(String layerUrl) {
        //获取图层图例名称数组（除文字标签）
        List<String> strings = getLegendLayerNameList(layerUrl);
        Layerr layerr = new Layerr(layerUrl, strings);

        return layerr;
    }

    //获取图层图例名称数组（除文字标签）
    private List<String> getLegendLayerNameList(String layerUrl) {
        //如果没有文字标签，则返回空数组代表显示全部图例
        List<String> legendLayerNameList = new ArrayList<>();
        JSONArray jsonArray = getLayersRJson(layerUrl);
        boolean bool = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
            for (int j = 0; j < layers.size(); j++) {
                JSONObject layer = layers.getJSONObject(j);
                JSONObject datasetInfo = layer.getJSONObject("datasetInfo");
                String layerName = datasetInfo.getString("name") + "@" + datasetInfo.getString("dataSourceName");
                //获取图层过滤条件
                String name = layer.getString("name");
                name = name.replace("#", ".");
                String legendLayerName = name + "@@" + layerName;
                String ugcLayerType = layer.getString("ugcLayerType");
                if (ugcLayerType.equals("THEME")) {
                    if ("LABEL".equals(layer.getJSONObject("theme").getString("type"))) {
                        //文字标签
                        bool = true;
                    } else {
                        legendLayerNameList.add(legendLayerName);
                    }
                } else {
                    legendLayerNameList.add(legendLayerName);
                }
            }
        }
        if (bool == false) {//无文字标签显示全部图例
            legendLayerNameList = new ArrayList<>();
        }

        return legendLayerNameList;
    }

    //获取临时图层url
    private String getSqlTempLayer(String layerUrl, String sqlText,boolean showLabelBool) {
        String resultUrl = layerUrl;
        if (PlatformObjectUtils.isNotEmpty(sqlText)) {
            JSONArray jsonArray = getLayersRJson(layerUrl);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
                for(int j=0;j<layers.size();j++){
                    JSONObject layer = layers.getJSONObject(j);
                    layer.put("displayFilter",sqlText);
                    if(showLabelBool==false && layer.getString("ugcLayerType")=="THEME"){
                        if(layer.getJSONObject("theme").getString("type")=="LABEL"){//文字标签子图层
                            layer.put("visible",showLabelBool);
                        }
                    }
                }
            }
            String jsonStr = JSON.toJSONString(jsonArray);
            JSONObject resultObj = postTempLayersSet(layerUrl,jsonStr);
            String newResourceID = resultObj.getString("newResourceID");
            String newResourceLocation = resultObj.getString("newResourceLocation");
            if (PlatformObjectUtils.isNotEmpty(newResourceLocation)) {
                resultUrl = newResourceLocation.replace(".rjson","");
            }
        }
        return resultUrl;
    }

    private JSONArray getLayersRJson(String layerUrl) {
        try {
            String dataUrl = layerUrl + "/layers.rjson";
            if (layerUrl.indexOf("tempLayersSet") != -1) {
                dataUrl = layerUrl + ".rjson";//临时图层
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
            JSONArray body = JSON.parseArray(jsonObject.getString("body"));
            if (body == null) {
                return null;
            }
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject postTempLayersSet(String layerUrl, String jsonStr){
        JSONObject result = new JSONObject();
        String dataUrl = layerUrl + "/tempLayersSet.rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
        JSONObject body = JSON.parseObject(jsonObject.getString("body"));
        if (body == null) {
            return null;
        }
        result = body;

        return result;
    }

    //根据dictCode、任务ID获取临时图层URL的Map
    public Map<String,String> getTempLayerUrlMapByDictCode(String dictCode,LegendVo legendVo){
        Map<String,String> tempLayerUrlMap = new HashMap<>();
        if ("DrawSeismicInfluence".equals(dictCode)) {//地震烈度图
            String tempLayerUrl = getTempLayerUrlByDataType("xzch_draw_seismic_influence",legendVo);
            tempLayerUrlMap.put("xzch_draw_seismic_influence",tempLayerUrl);
            String tempLayerUrl2 = getTempLayerUrlByDataType("xczh_seismic_event_management",legendVo);
            tempLayerUrlMap.put("xczh_seismic_event_management",tempLayerUrl2);
            String tempLayerUrl3 = getTempLayerUrlByDataType("jc_fault",legendVo);
            tempLayerUrlMap.put("jc_fault",tempLayerUrl3);
        }
        return tempLayerUrlMap;
    }

    //根据数据类型、任务ID获取临时图层URL
    public String getTempLayerUrlByDataType(String dataType,LegendVo legendVo){
        String tempLayerUrl = "";
        String layerUrl = "";
        String sqlText = "";
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        String xsemId = legendVo.getXsemId();//事件ID
        String faultVersion = legendVo.getFaultVersion();
        if(dataType.equals("xzch_draw_seismic_influence")){//地震烈度图绘制数据
            layerUrl = url + "/map-fxfzxczh/rest/maps/xzch_draw_seismic_influence@fxfzxczh";
            sqlText = "xsem_id='"+xsemId+"' and del_flag='0'";
        }else if(dataType.equals("xczh_seismic_event_management")){//地震事件震中
            layerUrl = url + "/map-fxfzxczh/rest/maps/xczh_seismic_event_management@fxfzxczh";
            sqlText = "xsem_id='"+xsemId+"' and del_flag='0'";
        }else if(dataType.equals("jc_fault")){//断层
            layerUrl = url + "/map-datacenter/rest/maps/jc_fault@datacenter";
            sqlText = "data_version='"+faultVersion+"' and del_flag='0'";
        }
        if (PlatformObjectUtils.isNotEmpty(layerUrl) && PlatformObjectUtils.isNotEmpty(sqlText)) {
            //获取临时图层
            tempLayerUrl = getSqlTempLayer(layerUrl, sqlText,true);
            System.out.println(dataType+"临时图层："+tempLayerUrl);
        }
        return tempLayerUrl;
    }

    public String getTitleByDictCodeTask(LegendVo legendVo,MapTemplate mapTemplate){
        String title = mapTemplate.getDictType();//标题
        String dictCode = mapTemplate.getDictCode();//出图类型字典code
        String xsemId = legendVo.getXsemId();//事件id
        EarEveManage earEveManage = legendVo.getEarEveManage();//地震事件
        if (earEveManage!=null){
            String epicentralSite = earEveManage.getEpicentralSite();//震中位置
            String magnitude = earEveManage.getMagnitude();//震级
            if ("DrawSeismicInfluence".equals(dictCode)) {//地震烈度图
                title = epicentralSite + magnitude + "级地震烈度图";
            }
        }

        return title;
    }
}
